#include "connectfour.h"
#include "gameboard_impl.h"
#include <algorithm>
#include <iostream>

//when you enter an invalid column,(invalid int like 3', the program run into dead loop)

namespace CS270Game {
const char tokens[] = { ' ', 'X', 'O'};
// Returns whether or not the move is valid (column is in bounds and there is 
// space to insert a token.)  
// If the move is valid, inserts the token at the designated column.
bool ConnectFour::CFBoard::makeMove(int col, ConnectFour::CFToken player) {
  //FIXME:  Implement making a move - remember not every move is valid
	bool b_ret = false;
	if (col < 0 || col >= numCols()) {
		return b_ret;
	}
	for (int i = 0; i < numRows(); ++i) {
		if ((*this)[i][col] == ConnectFour::EMPTY) {
			(*this)[i][col] = player;
			b_ret = true;
			break;
		}
	}
	return b_ret;
}

void ConnectFour::CFBoard::printBoard() {
  std::cout << std::endl;
  for (int i = CFBOARDSIZE_Y-1; i >= 0; i--) {
    std::cout << " | ";
    for (int j = 0; j < CFBOARDSIZE_X; j++) {
      std::cout << tokens[theBoard[i][j]] << ' '; 
    }
    std::cout << '|' << std::endl;
  }
  std::cout << " + - - - - - - - +" << std::endl;
  std::cout << "   0 1 2 3 4 5 6  " << std::endl;
  std::cout << std::endl;
}

bool ConnectFour::CFBoard::isFull() {
  //FIXME:  Sometimes the board is actually full
	bool b_ret = true;
	for (int i = 0; i < numRows(); i++) {
		for (int j = 0; j < numCols(); j++) {
			if ((*this)[i][j] == ConnectFour::EMPTY) {
				b_ret = false;
				break;
			}
		}
		//The board should not be full at any point
	}
	return b_ret;
}

//Examine the connect four board and determine if there is a winner
int ConnectFour::CFBoard::isWin() {
  // enum will convert to an integer cleanly if you return RED or BLACK
  // Take a look at methods provided by the base gameboard class!  This 
  // function shouldn't be more than a few lines
  //FIXME:
	int i_ret = -1;
	if (findLines(BLACK, 4)) {
		i_ret = BLACK;
	}
	else if (findLines(RED, 4)) {
		i_ret = RED;
	}
	/*else {
		i_ret = 0;
	}*/
  //No wins detected, despite our best efforts.
  return i_ret;
}

}
